﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using MacomberMapSystem.Common.Serialization;
using System.IO;
using MacomberMapSystem.Common.Database;
using MacomberMapSystem.Common.CIM;

namespace MacomberMapSystem.Common.Processing
{
    /// <summary>
    /// This class writes out an XML file containing our information for our kiosk
    /// </summary>
    public class CIM_Kiosk_Exporter: CIM_Processor
    {
       
        #region Initialization
        /// <summary>
        /// Initialize our kiosk exporter
        /// </summary>
        /// <param name="xElem"></param>
        /// <param name="NamedParameters"></param>
        /// <param name="Repository"></param>
        public CIM_Kiosk_Exporter(XmlElement xElem,Dictionary<String, Object> NamedParameters, MM_Repository Repository )
            : base(xElem, NamedParameters, Repository)
        { }
        #endregion

        /// <summary>
        /// Initialize a new process
        /// </summary>
        public override string ProcessName
        {
            get { return "Kiosk XML exporter"; }
        }

        /// <summary>
        /// Execute our process, writing out our data
        /// </summary>
        /// <param name="DbConn"></param>
        /// <returns></returns>
        public override CIM_Processor.enumProcessState InitiateProcess(Database.MM_Database_Connector DbConn)
        {
              //First, build our list of elements to be processed
              MM_Database_Model Model = NamedParameters["Model"] as MM_Database_Model;

              String TargetFolder = NamedParameters["TargetFolder"].ToString();
              String TargetFileName = NamedParameters["TargetFileName"].ToString();


              //Create our database export code
              String TargetFile = Path.Combine(TargetFolder, Path.GetFileNameWithoutExtension(TargetFileName) + ".sql");
              String TargetFile2 = Path.Combine(TargetFolder, Path.GetFileNameWithoutExtension(TargetFileName) + "-FuelMix.xml");

             using (StreamWriter sW = new StreamWriter(TargetFile,false, new UTF8Encoding(false)))
             using (XmlTextWriter xW = new XmlTextWriter(TargetFile2, new UTF8Encoding(false)))
             {
                 sW.WriteLine("DELETE FROM UnitFuelTypes;");
                 xW.WriteStartDocument();
                 xW.WriteStartElement("Units");
                 foreach (CIM_Element Elem in Model.ElementsOfType("cim:SynchronousMachine"))
                 {
                     sW.WriteLine("INSERT INTO UnitFuelTypes (Substation,Name,CombinedName,FuelType) VALUES ('{0}','{1}','{0}.{1}','{2}')", Elem.Substation.Name, Elem.Name, Elem.PrimaryFuelType);
                     xW.WriteStartElement("Unit");
                     xW.WriteAttributeString("Substation", Elem.Substation.Name);
                     xW.WriteAttributeString("Name", Elem.Name);
                     xW.WriteAttributeString("PrimaryFuelType", Elem.PrimaryFuelType);
                     xW.WriteEndElement();
                 }
                 xW.WriteEndElement();
                 xW.WriteEndDocument();

             }

              using (XmlTextWriter xW = new XmlTextWriter(Path.Combine(TargetFolder, TargetFileName), new UTF8Encoding(false)))
              {
                  xW.Formatting = Formatting.Indented;
                  xW.WriteStartDocument();
                  xW.WriteStartElement("Units");
                  xW.WriteAttributeString("Model", Model.ModelClass);
                  xW.WriteAttributeString("FileName", Model.CIMFileName);
                  xW.WriteAttributeString("ExportedOn", XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.Unspecified));
                  foreach (CIM_Element Elem in Model.ElementsOfType("cim:SynchronousMachine"))
                  {
                      xW.WriteStartElement("Unit");
                      xW.WriteAttributeString("Substation", Elem.Substation.Name);
                      xW.WriteAttributeString("Name", Elem.Name);
                      xW.WriteAttributeString("Voltage", Elem.VoltageLevel.Name);
                      CIM_Element Unit = Elem.ParseSingle("*Unit", Model);
                      if (Unit.ParseSingle("etx:DCTie", Model) != null)
                          xW.WriteAttributeString("FuelType", "DC Tie");
                      else if (Unit.Attributes["etx:GeneratingUnit.PrimaryFuelType"].EndsWith(".NA"))
                          xW.WriteAttributeString("FuelType", Unit.Attributes["etx:GeneratingUnit.PrimaryFuelType"]);
                      else
                          xW.WriteAttributeString("FuelType", Unit.Attributes["etx:GeneratingUnit.PrimaryFuelType"]);
                      xW.WriteAttributeString("WeatherZone", Elem.Substation.ParseSingle("cim:SubGeographicalRegion", Model).Name);
                      xW.WriteAttributeString("LoadZone", Elem.Substation.ParseSingle("etx:SettlementLoadZone", Model).Name);
                      xW.WriteEndElement();
                  }


                  xW.WriteEndElement();
                  xW.WriteEndDocument();
              }

            return enumProcessState.Completed;
        }
    }
}
